package main.leetcode.clockin.March;

/**
 * 695.岛屿的最大面积
 *
 * <p>给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
 *
 * <p>找到给定的二维数组中最大的岛屿面积。(如果没有岛屿，则返回面积为0。)
 *
 * <p>示例 1:
 *
 * <p>[ [0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0],
 * [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0],
 * [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]]
 *
 * <p>对于上面这个给定矩阵应返回 6。注意答案不应该是11，因为岛屿只能包含水平或垂直的四个方向的‘1’。
 *
 * <p>示例 2:
 *
 * <p>[[0,0,0,0,0,0,0,0]] 对于上面这个给定的矩阵, 返回 0。
 *
 * <p>注意: 给定的矩阵grid 的长度和宽度都不超过 50。
 *
 * <p>来源：力扣（LeetCode） 链接：https://leetcode-cn.com/problems/max-area-of-island
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class day15 {
    public static void main(String[] args) {
        System.out.println(
                new day15()
                        .maxAreaOfIsland(
                                new int[][] {
                                    {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
                                    {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
                                    {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
                                    {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
                                    {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
                                    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
                                    {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
                                    {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}
                                }));
    }

    public int maxAreaOfIsland(int[][] grid) {
        int m = grid.length;
        if (m == 0) return 0;
        int n = grid[0].length;
        int res = 0;
        //        int[][] clone = grid.clone();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (grid[i][j] > 0) res = Math.max(dfs(grid, m, n, i, j), res);
        return res;
    }

    private int dfs(int[][] grid, int m, int n, int i, int j) {
        if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || grid[i][j] < 1) return 0;
        int sum = 1;
        grid[i][j] = 0; // 取代了isVisited判断该土地已被遍历过
        sum += dfs(grid, m, n, i - 1, j);
        sum += dfs(grid, m, n, i + 1, j);
        sum += dfs(grid, m, n, i, j - 1);
        sum += dfs(grid, m, n, i, j + 1);
        return sum;
    }
}
